package cn.itcast.demo;

import cn.itcast.domain.Items;
import cn.itcast.domain.Orders;
import cn.itcast.domain.User;
import cn.itcast.mapper.OrdersMapper;
import cn.itcast.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class UserDemo {
    private SqlSession sqlSession = null;
    private UserMapper mapper = null;
    @Before
    public  void  before() throws Exception{
        //读取mybatis核心配置文件
        InputStream is = Resources.getResourceAsStream("SqlConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        sqlSession = sessionFactory.openSession();
         mapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void after(){
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void findOrdersAndUsername(){
        List<User> userList = mapper.findAll();
        for (User user : userList) {
            List<Orders> ordersList = user.getOrdersList();
            System.out.println("用户姓名 :" + user.getUsername());
            for (Orders orders : ordersList) {
                System.out.println("订单编号:" + orders.getNumber());
            }
        }
    }
    /*关联查询*/
    @Test
    public void findUser(){
        List<User> userList = mapper.findUser();

        for (User user : userList) {
            List<Orders> ordersList = user.getOrdersList();
            System.out.println("用户姓名 :" + user.getUsername());
            for (Orders orders : ordersList) {
                System.out.println("订单编号:" + orders.getNumber());
            }
        }
    }

    @Test
    public void findUserAndOrdersAndItems(){
        List<User> userList = mapper.findUserAndOrdersAndItems();

        for (User user : userList) {
            List<Orders> ordersList = user.getOrdersList();
            System.out.println("用户姓名 :" + user.getUsername());
            for (Orders orders : ordersList) {
                System.out.println("订单编号:" + orders.getNumber());
                List<Items> itemsList = orders.getItemsList();
                for (Items items : itemsList) {
                    System.out.println("商品名称:" + items.getName()) ;
                }
            }
        }
    }
}

















